<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-11-06 13:07:07
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Http\Services\Market;

use App\Http\Services\Service;
use App\Models\MpcBacthStorage;
use App\Models\MpcSummaryStorage;
use App\Repositories\MarketComplaintRepository;
use App\Repositories\MarketDeliveryDetailsPackRepository;
use App\Repositories\MarketDeliveryExtraCostRepository;
use App\Repositories\MarketDeliveryRepository;
use App\Repositories\MarketDeliveryDetailsRepository;
use Illuminate\Support\Facades\DB;

/**
 * @property MarketDeliveryRepository $repository
 * @property MarketDeliveryDetailsRepository $details  
 * @property MarketDeliveryDetailsPackRepository $pack  
 * @property MarketDeliveryExtraCostRepository $ex_cost 
 */
class DeliveryService extends Service
    {
    public function boot(
        MarketDeliveryRepository $repository,
        MarketDeliveryDetailsRepository $details,
        MarketDeliveryDetailsPackRepository $pack,
        MarketDeliveryExtraCostRepository $ex_cost
    ) {
        $this->repository = $repository;
        $this->details    = $details;
        $this->pack       = $pack;
        $this->ex_cost       = $ex_cost;
        }

    public function info()
        {
        return $this->repository
            ->setRelation(['customer','extra_cost_details', 'carry' => ['company'], 'car' => ['company'], 'details' => ['material', 'location', 'packs','unit'],'attachments'])
            ->condition(request())
            ->getOne();
        }
    public function deleveryinfo()
        {
        return $this->details
            ->setRelation(['customer', 'material', 'location', 'packs'])
            ->condition(request())
            ->getOne();
        }
    public function list()
        {
        return $this->repository->condition(request())->getGrid();
        }
    public function pack()
        {
        return $this->pack->condition(request())->getGrid();
        }
    public function details()
        {
        // DB::enableQueryLog();
        $data = $this->details->where("code", "like", "L%")->condition(request())->getGrid();
        // dd(DB::getQueryLog());
        return $data;
        }
  protected function setRowColor()
        {
            $request=request();
            $gdata= $this->details->whereId( $request->id)->first();
            $gdata->bgrgb=$request->color;
            return $gdata->save();
        }
    public function detailsall()
        {
        // DB::enableQueryLog();
        $data = $this->details->condition(request())->getGrid();
        // dd(DB::getQueryLog());
        return $data;
        } 
    protected function save()
        {
        $data = request()->toArray();

        $code = $data['code'] ?? "";
        if ($code != "") {
            $gdata = $this->repository->whereCode($code)->getOne();

            if ($gdata->status_id != '0') {
                fail("订单状态[{$gdata->status->name}],禁止编辑");
                }
            }
        $data['status_id'] = 0;
        if (count($data['details'] ?? []) == 0) {
            fail("订单状态明细不能为空！");
            } 
        //合计订单包/重
        $se_quantity                = $quantity = $auxiliary_quantity = $amount = $se_amount =$m_quantity= $mi_quantity=0;
        
        $data['details']            = array_map(function ($v) use ($data, &$quantity,&$m_quantity,&$mi_quantity, &$se_quantity, &$auxiliary_quantity, &$amount, &$se_amount)
            {
                $quantity += $v['quantity'];
                $m_quantity += $v['m_quantity'];
                $mi_quantity += $v['mi_quantity'];
            $se_quantity += $v['se_quantity'];
            $v['se_amount']=$v['amount'];
            $v['se_price']=$v['price'];
            $amount += $v['amount'];
            $se_amount += $v['se_amount'];
            $v['red_quantity']     = $v['quantity'];
            $auxiliary_quantity += $v['auxiliary_quantity'];
            $v['main_customer_id'] = $data['customer_id']; 
            unset(
                $v['iscustomer'],
                $v['in_quantity'],
                $v['in_auxiliary_quantity'],
                $v['occupy_quantity'],
                $v['occupy_auxiliary_quantity'],
                $v['out_quantity'],
                $v['out_auxiliary_quantity'],
                $v['available_quantity'],
                $v['available_auxiliary_quantity'],
                $v['company_id'], 
            );
            return $this->details->autosave($v);
            }, $data['details']);
            $data['quantity']           = $quantity;
            $data['mi_quantity']           = $mi_quantity;
            $data['m_quantity']           = $m_quantity;
        $data['auxiliary_quantity'] = $auxiliary_quantity;
        $data['amount']             = $amount;
        $data['se_amount']          = $se_amount;
        $data['se_quantity']        = $se_quantity;
        $gdata['department_id']     = auth()->user()->department_id;
        $gdata                      = $this->repository->autosave($data);

        $this->saveCar($gdata);
        $this->saveCarry($gdata);
        $gdata->details->filter(function ($v) use ($gdata)
            {
            $v->code          = $gdata->code;
            $v->salesman_id   = $gdata->salesman_id;
            $v->department_id = $gdata->department_id;
            $v->billdate      = $gdata->billdate;
            $v->tax_id        = $gdata->tax_id;
            $v->attachment    = $gdata->attachment;
            $v->save();
            });
        return true;
        }
    private function saveCarry($model)
        {
        $model->details->filter(function ($row) use ($model)
            {
            if ($model->carry_id == $row->carry_id)
                return;
            else if ($row->carry_id > 0)
                $row->removeCarryItem();

            if ($model->carry_id > 0)
                $row->addCarryItem($model->carry_id, $row->main->code);

            });
        }
    private function saveCar($model)
        {

        $model->details->filter(function ($row) use ($model)
            {
            if ($model->car_id == $row->car_id)
                return;
            else if ($row->car_id > 0)
                $row->removeCarItem();
            if ($model->car_id > 0)
                $row->addCarItem($model->creator->department?->name ?? "JG", $model->customer->name, $model->car_id);
            });
        }

    protected function audit()
        {

        $ids=$this->details->whereIn("id",$this->getRequestIds())->pluck("code");  
        $this->repository->whereIn("code",$ids)->get()->filter(function ($v)
                {
                if ($v->status_id && $v->status_id != 0) {
                    fail("单据{$v->code}{$v->status->name},审核失败!");
                    }
                auditSave($v);
                $v->details->filter(function ($vv)
                    {
                    auditSave($vv);
                    $vv->packs->filter(function ($vvv) use ($vv)
                        {
                            $vvv->status_id=1;
                        $vvv->setWhere(
                            [
                                'batchno'     => $vvv->batchno,
                                'type_id'     => $vv->type_id,
                                'reel'        => $vvv->reel,
                                'location_id' => $vvv->location_id,
                                'dyelot'        => $vvv->dyelot??"",
                                'craft'       => $vvv->craft??"",
                                'sample_data' =>$vvv->sample_data??"",
                                'orderno'     =>$vvv->orderno??"",
                                'unit_id'     =>$vvv->unit_id??"",
                            ]
                        )->useStorage('零售发货', $vv->code)->subStorage();
                        });
                      
                    });

                });
        }

    protected function noaudit()
        {
        $this->repository->whereHas("details", function ($query)
            {
            $query->where("id", $this->getRequestIds());
            })->get()->filter(function ($v)
                {
                if ($v->status_id && $v->status_id != 1) {
                    fail("单据{$v->code}{$v->status->name},审核失败!");
                    }
                auditSave($v, false);
                $v->details->filter(function ($vv)
                    {
                    auditSave($vv, false);
                    $vv->packs->filter(function ($vvv)
                        {
                            $vvv->status_id=0;
                        $vvv->nosubStorage()->nouseStorage();
                        });

                    });
                });
        }
    protected function delete()
        {
        return $this->repository->whereHas("details", function ($query)
            {
            $query->where("id", $this->getRequestIds());
            })->get()->filter(function ($v)
                {
                if ($v->status_id != 0) {
                    fail("单据{$v->code}{$v->status->name},删除失败!");
                    }
                $v->details->filter(function ($vv)
                    {
                    $vv->packs->filter(fn($vvv) => $vvv->delete());
                    $vv->delete();
                    });
                //删除附件
                $this->repository->deleteAttachment($v)->delete();
                });

        }
    protected function financemain()
        {
        return $this->repository->whereIn("id", $this->getRequestIds())->finance(); 
        }
    protected function finance($ids=null)
        {
        $list    = $this->details->whereIn("id", $ids??$this->getRequestIds())->get();
        $red_ids = $list->pluck("main_id");
        $codes   = $list->pluck("code");
        // DB::enableQueryLog();
        $this->repository->whereIn("code", $codes)->finance();
        // dd(DB::getQueryLog());1
        MarketComplaintRepository::whereIn("id", $red_ids)->finance();
        }
        protected function saveAndFinace(){
            $data = request()->toArray();
    
            $code = $data['code']; 
                $gdata = $this->repository->whereCode($code)->getOne(); 
                if ($gdata->status_id != '1') {
                    fail("订单状态[{$gdata->status->name}],禁止审核");
                    }
            $ids=[];
            $extra_amount=0;
            array_filter($data['extra_cost_details'],function($v)use($code,&$ids,&$extra_amount){
                $v['code']=$code;
                $extra_amount +=is_numeric($v['amount'])?$v['amount']:0;
                $ids[]= $this->ex_cost->autosave($v)->id;
            } );
            $this->ex_cost->whereCode($code)->whereNotIn("id",$ids)->get()->filter(function($v){
                $v->delete();
            });
            $ids=[]; 
              //合计订单包/重  
           $se_quantity   = $se_amount = 0;
            array_map(function ($v) use ( &$se_quantity, &$se_amount,&$ids)
                {  
                    $detail_m=$this->details->whereId($v['id'])->first();
                    $detail_m->se_quantity=$v['se_quantity'];
                    $detail_m->mi_quantity=$v['mi_quantity'];
                    $detail_m->m_quantity=$v['m_quantity'];
                    $detail_m->se_price=$detail_m->price=$v['price'];
                    $detail_m->se_amount=$detail_m->amount=$v['amount'];
                    $detail_m->save();
                    $ids[]=$detail_m->id;
                    $se_amount+=$v['amount'];
                    $se_quantity+=$v['se_quantity'];
                }, $data['details']);   
                $gdata->se_quantity=  $se_quantity;
                $gdata->se_amount= $se_amount;  
                $gdata->billdate= $data['billdate'];    
                $gdata->extra_amount=$extra_amount;
                $gdata->save(); 
                if($data['flage']==2) 
                return $this->finance( $ids);
            else{
                return $gdata;  
            }
        }
    public function printReport()
        {
        $res = [];
        $this->repository->whereHas("details", function ($query)
            {
            $query->where("id", $this->getRequestIds());
            })
            ->first()->details->filter(function ($v) use (&$res)
                {
                $v->material;
                $v->customer;
                $v->unit;
                $v->main;
                $i                  = 0;
                $k                  = count($res);
                $row                = null;
                $quantity           = 0;
                $auxiliary_quantity = 0;
                $v->packs->filter(function ($vv) use (&$v, &$i, &$k, &$row, &$res, &$quantity, &$auxiliary_quantity)
                    {
                    $auxiliary_quantity++;
                    if ($row == null) {
                        $row = $vv->toArray();
                        }
                    $row['Column' . ($i++)] = (int) $vv->quantity;
                    $quantity += (int) $vv->quantity;
                    if ($i == 10) {
                        $row['auxiliary_quantity'] = $auxiliary_quantity;
                        $row['quantity']           = $quantity;
                        $row['price']              = $v->price;
                        $row['amount']             = $v->price * $quantity;
                        if(isNotEmpty($v->custno)){ 
                            $row['material']['name']=$v->custno;
                        }
                        $res[$k++]                 = array_merge($v->toArray(), $row);
                        $auxiliary_quantity        = $quantity = $i = 0;
                        $row = null;
                        }
                    });
                if ($i <= 9 && $row) {
                    $row['auxiliary_quantity'] = $auxiliary_quantity;
                    $row['quantity']           = $quantity;
                    $row['price']              = $v->price;
                    $row['amount']             = $v->price * $quantity;
                    if(isNotEmpty($v->custno)){
                        $row['material']['name']=$v->custno;
                    }
                    $res[]                     = array_merge($v->toArray(), $row);
                    }
                });
        return createReport($res);
        }
    }